﻿using System;
using System.Collections.Generic;
using MySql.Simple.Mapper.Attributes;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Finders
{
    /// <summary>
    /// Finds the SQL column names to store a classes data in.
    /// </summary>
    public static class ForeignKeyFinder
    {
        /// <summary>
        /// Finds the specified target.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public static IList<ForeignKey> Find(Type target)
        {
            var keys = new List<ForeignKey>();

            var properties = target.GetProperties();

            var sourceTableName = TableNameFinder.Find(target);
            var sourceColumns = ColumnFinder.Find(target);

            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes(typeof(ForeignKeyAttribute), true);

                foreach (var attribute in attributes)
                {
                    var foreignKeyAttribute = (ForeignKeyAttribute)attribute;

                    var destinationTableName = TableNameFinder.Find(foreignKeyAttribute.Type);
                    var destinationColumns = ColumnFinder.Find(foreignKeyAttribute.Type);

                    var foreignKey = new ForeignKey
                                     {
                                         SourceColumn = sourceColumns.Find(property).Name,
                                         SourceTable = sourceTableName,
                                         DestinationColumn = destinationColumns.PrimaryKeyName,
                                         DestinationTable = destinationTableName
                                     };

                    keys.Add(foreignKey);
                }
            }

            return keys;
        }
    }
}